gadgets.util.registerOnLoadHandler(function(){
  ;(function($) {
    var prefs = new gadgets.Prefs();
    var tabs = new gadgets.TabSet(g_module_id, prefs.getString("selected_tab"));
    var view_params = gadgets.views.getParams();
    var sports = {
      "Col Fball": "ncf",
      "NFL": "nfl",
      "MLB": "mlb",
      "NBA": "nba",
      "NHL": "nhl",
      "Col Hoops": "ncb"
    };
    
    function change_view(to,params) {
//      if(gadgets.views.getCurrentView().getName() != to) {
        gadgets.views.requestNavigateTo(new gadgets.views.View(to), params);
//      }
    };
    
    function Game(node) {
      var _this = this;
      var homeTeam = {};
      var awayTeam = {};
      
      $(node).children().each(function(i,el){ 
        var property = this.nodeName.replace("espn:","");
        var prop_name = "";
        
        if( property.match(/^home/) ){
          prop_name = property.replace("homeTeam","").replace(/^home/,"");
          homeTeam["get"+prop_name.substring(0,1).toUpperCase() + prop_name.substring(1)] = function(){
            return $(el).text();
          }
        } else if( property.match(/^away/) ){
          prop_name = property.replace("awayTeam","").replace(/^away/,"");
          awayTeam["get"+prop_name.substring(0,1).toUpperCase() + prop_name.substring(1)] = function(){
            return $(el).text();
          }
        } else {
          prop_name = property.replace("game","");
          _this["get"+prop_name.substring(0,1).toUpperCase() + prop_name.substring(1)] = function(){
            return ($(el).text()+'').replace(/^null$/,"").replace(/^0:00$/,"");
          }
        }
      });
      
      
      this.getHomeTeam = function() {
        return homeTeam;
      };
      
      this.getAwayTeam = function() {
        return awayTeam;
      };
      
    }
    
    function fetch_feed(tab_id) {
      var sport_name = tabs.getSelectedTab().getName();
      var sport = sports[sport_name];
      var url = "http://feeds.espn.go.com/"+sport+"/widgets/s?c=games&a=feed";
      var params = {};
      
      params[gadgets.io.RequestParameters.CONTENT_TYPE] = gadgets.io.ContentType.DOM;  
      
      prefs.set("selected_tab",sport_name);
      prefs.set("selected_sport",sport);
      
      make_cached_request(url, response, params, 120);
      //gadgets.io.makeRequest(url, response, params);
    };

    function response(obj) {
      var css_stati = {
        1:"pre",
        2:"in",
        3:"post"
      };
      var selectors = [];
      var dates = [];
      $(tabs.getSelectedTab().getContentContainer()).html(
        '<ul>'+$.map($(obj.data).find("item"),function(node){
          var game = new Game(node);
          var awayTeam = game.getAwayTeam();
          var homeTeam = game.getHomeTeam();

          selectors.push("#game-"+game.getId() + " ." + css_stati[game.getStatusId()]);
          dates.push(game.getDate().split(",")[0]);

          return '<li class="game" id="game-'+game.getId()+'">\
            <div class="note">'+game.getNote()+'</div>\
            <div class="date">'+game.getDate().split(",")[0]+'</div>\
            <div class="time pre"><a class="expando" href="'+game.getContentUrl()+'">'+(game.getDate().split(",")[1]+"").replace(/^ \d+ /,"")+'</a></div>\
            <div class="tv pre in">'+game.getTv()+'</div>\
            <div class="statusText post"><a class="expando" href="'+game.getContentUrl()+'">'+game.getStatusText()+'</a></div>\
            <div class="clock in"><a class="expando" href="'+game.getContentUrl()+'">'+game.getClock()+'</a></div>\
            <div class="awayTeam">\
              <div class="teamMeta">\
                <img width="16" height="16" src="'+awayTeam.getLogo().replace("/lrg/","/sml/")+'" alt="" />\
                <a class="displayName" href="'+awayTeam.getClubhouse()+'">'+awayTeam.getDisplayName()+'</a>\
                <span class="apRank">'+(awayTeam.getAPRank ? awayTeam.getAPRank() : '')+'</span>\
              </div>\
              <div class="pre winLoss">\
                <span class="wins">'+awayTeam.getWins()+'</span>-<span class="losses">'+awayTeam.getLosses()+'</span>\
              </div>\
              <div class="score in post">'+awayTeam.getScore()+'</div>\
            </div>\
            <div class="homeTeam">\
              <div class="teamMeta">\
                <img width="16" height="16" src="'+homeTeam.getLogo().replace("/lrg/","/sml/")+'" alt="" />\
                <a class="displayName" href="'+homeTeam.getClubhouse()+'">'+homeTeam.getDisplayName()+'</a>\
                <span class="apRank">'+(homeTeam.getAPRank ? homeTeam.getAPRank() : '')+'</span>\
              </div>\
              <div class="pre winLoss">\
                <span class="wins">'+homeTeam.getWins()+'</span>-<span class="losses">'+homeTeam.getLosses()+'</span>\
              </div>\
              <div class="score in post">'+homeTeam.getScore()+'</div>\
            </div>\
          </li>';
        }).join("")+'</ul>'
      ).find("div:empty").remove();
      
      $(selectors.join(",")).show();
      $.each(dates,function(i,date){
        $(tabs.getSelectedTab().getContentContainer()).find("div.date:contains('"+date+"')").not(":first").remove();
      });
      
      $(tabs.getSelectedTab().getContentContainer()).find("a").click(function(){
        if($(this).hasClass("expando")) {
          prefs.set("expando_url",$(this).attr('href'));
          change_view("canvas",{ url: $(this).attr('href') });
          return false;
        }
      });
    };
    
    function make_cached_request(url, callback, params, refreshInterval) {
      var ts = new Date().getTime();
      var sep = "?";
      if (refreshInterval && refreshInterval > 0) {
        ts = Math.floor(ts / (refreshInterval * 1000));
      }
      if (url.indexOf("?") > -1) {
        sep = "&";
      }
      url = [ url, sep, "nocache=", ts ].join("");
      gadgets.io.makeRequest(url, callback, params);
    }
    
    function fetch_html(obj) {
      // var header = $(obj.text).find(".mod-article-title").html();
      // var body = $.map($(obj.text).find(".article>p:not([class])"),function(el){ return "<p>"+ $(el).html() + "</p>"; }).join("").replace(/<p><\/p>/,"");
      var html = $(obj.text).find(".span-6:last").html();
      
      if(!html) {
        html = $(obj.text).find(".col-left").html();
      }
      
      $("#content").html(html).append($('<a style="display:block;" href="#">Back to Scores</a>').click(function(el){
        prefs.set("expando_url","");
        change_view("home");
        return false;
      }));
      $("#espnstlink").remove();
      $("a").attr("target","_blank");
      
      gadgets.window.adjustHeight();
    }
    
    if(gadgets.views.getCurrentView().getName().toLowerCase() == "home") {
      $("#content").hide();
      for(var i in sports){
        tabs.addTab(i, {
           contentContainer: document.getElementById(sports[i]),
           callback: fetch_feed
        });
      }
    } else {
      var params = {}; 
      
      if(!view_params.url) {
        view_params.url = (prefs.getString("expando_url") || $("a.expando:first").attr("href"));
      }
      
      $("#content").show();
      
      params[gadgets.io.RequestParameters.CONTENT_TYPE] = gadgets.io.ContentType.TEXT;
      make_cached_request(view_params.url, fetch_html, params, 120);
      //gadgets.io.makeRequest(view_params.url, fetch_html, params);
    }
    
  })(jQuery);
});